package com.myblog.demo.controller;

import com.myblog.demo.common.AjaxResult;
import com.myblog.demo.common.UserSessionTools;
import com.myblog.demo.entity.Message;
import com.myblog.demo.entity.UserInfo;
import com.myblog.demo.service.FollowService;
import com.myblog.demo.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private MessageService messageService;

    @Autowired
    private FollowService followService;

    /**
     * 根据会话id获取指定会话的消息列表
     *
     * @param sessionId 会话id
     * @param friendId  会话对象用户id
     * @param request   HttpServletRequest
     * @return AjaxResult
     */
    @RequestMapping("/get_message_list")
    public AjaxResult getMessageListBySessionId(Integer sessionId, Integer friendId, HttpServletRequest request) {
        // 参数校验
        if (sessionId == null || sessionId <= 0 || friendId == null || friendId <= 0) {
            return AjaxResult.fail(-1, "参数错误！");
        }

        // 获取当前登录用户id
        UserInfo loginUser = UserSessionTools.getLoginUser(request);
        if (loginUser == null) {
            return AjaxResult.fail(-2, "当前用户未登录！");
        }

        int userId = loginUser.getId();

        // 判断二者是否互相关注，只有互相关注的用户才能进行聊天
        Boolean flag = followService.isFollowEachOther(userId, friendId);
        if (!flag) {
            // 两个用户没有互相关注，不能进行私信
            return AjaxResult.fail(-3, "只有互相关注的用户才能进行聊天！");
        }

        List<Message> messages = messageService.getMessageListBySessionId(sessionId);
        // 逆置
        Collections.reverse(messages);

        return AjaxResult.success(messages);
    }
}
